package net.jxtz.jxtzos.impl.achievement;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.jxtz.jxtzos.entity.achievements.Achievement;
import net.jxtz.jxtzos.entity.achievements.dto.InitAchieveList;
import net.jxtz.jxtzos.mapper.achievement.AchievementMapper;
import net.jxtz.jxtzos.service.achievement.AchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author a123
 */
@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {

    private List<Achievement> tabsTree = new ArrayList<>();

    @Override
    public List<Achievement> initTree() {
        tabsTree = achievementMapper.selectList(null);
        List<Achievement> tree = new ArrayList<>();
        for (Achievement achievement : getRootNode()) {
            achievement = buildChildTree(achievement);
            tree.add(achievement);
        }
        return tree;
    }

    /**
     * 递归创建子树形结构
     * @param child 子节点
     * @return 内嵌子节点的Achievement
     */
    private Achievement buildChildTree(Achievement child){
        List<Achievement> childs = new ArrayList<>();
        List<Achievement> tabsTree = this.tabsTree;
        for (Achievement achievement : tabsTree) {
            if (achievement.getFatherId().equals(child.getId())){
                childs.add(buildChildTree(achievement));
            }
        }

        child.setAchievements(childs);
        return child;
    }

    private List<Achievement> getRootNode(){
        List<Achievement> rootNodes = new ArrayList<>();
        for (Achievement achievement : tabsTree) {
            if (achievement.getFatherId() == 0){
                rootNodes.add(achievement);
            }
        }

        return rootNodes;
    }

    private final AchievementMapper achievementMapper;

    @Autowired
    public AchievementServiceImpl(AchievementMapper achievementMapper){
        this.achievementMapper = achievementMapper;
    }

}
